<script setup>
import {reactive} from 'vue'
import {useRouter} from 'vue-router'
import {message} from "@/util/util";
import {postRequest} from "@/util/api";

const loginForm = reactive({
  username: '',
  password: ''
});

const router = useRouter();

function login() {
  if (loginForm.username === "" || loginForm.password === "") {
    message("请输入用户名与密码后登录", "warning");
    return;
  }

  postRequest("/user/login", null, {
    username: loginForm.username.trim(),
    password: loginForm.password.trim()
  }, (res) => {
    localStorage.setItem("token", res.data.data.token);
    localStorage.setItem("refreshToken", res.data.data.refreshToken);
    localStorage.setItem("username", loginForm.username.trim());
    localStorage.setItem("password", res.data.data.password);
    localStorage.setItem("avatarUrl", res.data.data["avatarUrl"]);
    message(res.data.msg, "success");
    router.push({
      path: '/home'
    });
  });
}

function toRegister() {
  router.push({
    path: '/register'
  });
}
</script>

<template>
  <el-form :model="loginForm" class="login-container">
    <h3 class="login-title">系统登录</h3>
    <el-form-item>
      <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large" type="text"></el-input>
    </el-form-item>

    <el-form-item>
      <el-input v-model="loginForm.password" placeholder="请输入密码" show-password size="large"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button size="large" style="width: 100%" type="primary" @click="login">登录</el-button>
    </el-form-item>

    <el-form-item>
      <el-text class="register-btn" type="primary" @click="toRegister">注册</el-text>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  width: 350px;
  padding: 15px 30px;
  background: #fff;
  border: 1px solid #eeeaea;
  box-shadow: 0 0 25px #cac6c6;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-70%);
}

.login-title {
  margin: 0 auto 20px auto;
  text-align: center;
  color: lightskyblue;
  font-size: 24px;
}

.register-btn {
  &:hover {
    cursor: pointer;
    color: #87cefa;
  }
}
</style>
